package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.bytebuddy.asm.Advice;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author: 李旭
 * @create: 2021-08-24 11:33
 **/
@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;//有接口 没有实现类
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper  spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    //只写接口  底层动态代理 JDK Cglib 完成实现类  Sping的框架上已经学完了
    //查询一级分类集合
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }
    //查询二级分类集合  条件是一级分类的ID
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
           .eq("category1_id",category1Id));
    }
    //查询三级分类集合  条件是二级分类的ID
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id",category2Id));
    }
    //查询平台属性及属性值集合
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id,category2Id,category3Id);//Mybatis-plus  手写SQL才是无敌的
    }

    //保存平台属性及属性值
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //保存并返回主键ID
        baseAttrInfoMapper.insert(baseAttrInfo);
        //保存平台属性值
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        attrValueList.forEach(attrValue -> {
            //外键
            attrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(attrValue);
        });
    }
    //品牌列表查询 （分页） 每页数  当前页
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        return baseTrademarkMapper.selectPage(new Page(page,limit),null);
    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>()
          .eq("attr_id",attrId));
    }
    //查询商品列表  分页  根据三级分类ID进行查询
    @Override
    public IPage spuPage(Integer page, Integer limit, Long category3Id) {
        return spuInfoMapper.selectPage(new Page<SpuInfo>(page,limit),
                new QueryWrapper<SpuInfo>().eq("category3_id",category3Id));
    }
    //品牌集合  商品添加 显示下拉框
    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }
    //销售属性集合  商品添加  显示下拉框
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }
    //商品添加
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1:商品表 spu_info    1   保存成功之后返回主键ID
        spuInfoMapper.insert(spuInfo);
        //2:图片表  spu_image  N
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        spuImageList.forEach(spuImage -> {
            //商品ID的外键
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
        //3:销售属性表  spu_sale_attr N
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        spuSaleAttrList.forEach(spuSaleAttr -> {
            //商品ID的外键
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //4:销售属性值表  spu_sale_attr_value N
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.
                    getSpuSaleAttrValueList();
            spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                //外键
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                //销售属性名称
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });
    }
    //根据spuId查询图片列表
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>()
          .eq("spu_id",spuId));
    }
    //根据spuId查询销售属性及属性值集合
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }
    //添加sku
    @Override
    @Transactional
    public void saveSkuInfo(SkuInfo skuInfo) {
        //1:sku_info  保存返回主键
        skuInfoMapper.insert(skuInfo);
        //2:sku_image  多
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        skuImageList.forEach(skuImage -> {
            //外键
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        //3:sku_attr_value 表  平台属性 多
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        skuAttrValueList.forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //4:sku_sale_attr_value 销售属性及值表  多
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            //库存ID
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            //商品ID
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });

    }
    //查询SKU分页列表
    @Override
    public IPage skuListPage(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page<SkuInfo>(page,limit),null);
    }

    @Autowired
    private RabbitService rabbitService;

    //上架
    @Override
    @Transactional
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);// update sku_info set is_sale = 1 where id = skuId
        skuInfoMapper.updateById(skuInfo);
        //发消息通知ES索引库 添加索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.NOSALE);
        skuInfoMapper.updateById(skuInfo);
        //发消息通知ES索引库 删除索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    //根据SKUID查询库存信息  库存图片
/*    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(null != skuInfo){
            //图片
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                    .eq("sku_id", skuId));
            skuInfo.setSkuImageList(skuImageList);
        }
        return skuInfo;
    }*/

    @Autowired
    private RedisTemplate redisTemplate;//不是原生的RedisTemplate 被我们给改了






    //查询库存信息 添加缓存功能  缓存的三大问题
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //String cacheKey = "sku:" + skuId + ":info";//硬编码问题
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        //1、先查询Redis
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if(null == skuInfo){
            //1.1:缓存三大问题之一  缓存击穿   DB这个数据如果是热点数据
            String cacheKeyLock = RedisConst.SKUKEY_PREFIX + skuId
                    + RedisConst.SKULOCK_SUFFIX;
            //1.2  加锁  （过期不候）
            String uuid = UUID.randomUUID().toString();
            Boolean isLock = redisTemplate.opsForValue().
                    setIfAbsent(cacheKeyLock, uuid, 2, TimeUnit.SECONDS);
            if(isLock){
                //获取到锁了
                try {
                    //2、如果没有数据  查询DB
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if(null != skuInfo){
                        //图片
                        List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                .eq("sku_id", skuId));
                        skuInfo.setSkuImageList(skuImageList);
                        //3、保存缓存一份  缓存三大问题之一 缓存雪崩
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,RedisConst.SKUKEY_TIMEOUT
                                + new Random().nextInt(300),TimeUnit.SECONDS);// 1-5分钟  60S-300S
                    }else{
                        //缓存三大问题之一  缓存穿透
                        //解决：将空结果 保存在Redis缓存中  保存5分钟
                        skuInfo = new SkuInfo();//有对象  对象中没有属性
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,5, TimeUnit.MINUTES);
                    }
                } finally {
                    //解锁
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                    this.redisTemplate.execute(new DefaultRedisScript<>(script),
                            Collections.singletonList(cacheKeyLock), uuid);
                }
            }else{
                //未获取到锁
                try {
                    //休息 一会 儿
                    TimeUnit.SECONDS.sleep(2);
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        //4、如果有直接返回
        return skuInfo;

    }
    //一二三级分类  入参：三级分类ID
    //加缓存 ： Redisson框架来完成缓存三大问题之一的缓存击穿
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        String cacheKey = "baseCategoryView:" + category3Id
                + RedisConst.SKUKEY_SUFFIX;
        //1:先查询缓存
        BaseCategoryView baseCategoryView = (BaseCategoryView) redisTemplate.opsForValue().get(cacheKey);
        if(null == baseCategoryView){
            //1.1: 缓存三大问题之一  缓存击穿
            String cacheKeyLock = "baseCategoryView:" + category3Id +
                    RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheKeyLock);
            //lock.lock();//不见不散的锁
            //参数1：获取的锁的时间
            //参数2：锁的过期时间
            //参数3：单位
            try {
                boolean isLock = lock.tryLock(1, 2, TimeUnit.SECONDS);// 过期不候的锁
                if(isLock){
                    //获取到了锁
                    try {
                        //2:查询DB
                        baseCategoryView =  baseCategoryViewMapper.selectById(category3Id);
                        if(null != baseCategoryView){
                            //缓存三大问题之一：缓存雪崩
                            redisTemplate.opsForValue().set(cacheKey,baseCategoryView
                                    ,RedisConst.SKUKEY_TIMEOUT +
                                            new Random().nextInt(300),
                                    TimeUnit.SECONDS);
                        }else{
                            //缓存三大问题之一 ： 缓存穿透
                            baseCategoryView = new BaseCategoryView();
                            redisTemplate.opsForValue().set(cacheKey,baseCategoryView
                              ,5,TimeUnit.MINUTES);
                        }
                    } finally {
                        //解锁
                        lock.unlock();
                    }
                }else{
                    //未获取到锁
                    TimeUnit.SECONDS.sleep(2);
                    return (BaseCategoryView) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //缓存不为NULL直接返回
        return baseCategoryView;
    }

    ////单独查询商品价格  价格不允许缓存  要求实时更新
    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(null != skuInfo){
            return skuInfo.getPrice();
        }
        return null;
    }

    //销售属性及属性值（选中项）标红
    @Override
    //@Transactional //第一步：进入TransactionManager类 注入了数据源DataSource--》连接Mysql数据库  开启事务 begin tran...
    @GmallCache(prefix="getSpuSaleAttrListCheckBySku")   //自定义注解  第一步；进入GmallAspect类 在此类实现缓存+分布式锁
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        //第二步：执行此代码
        return spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(skuId,spuId);
    }
    //第三步：进入GmallAspect类 在此类实现缓存+分布式锁

    //点击销售属性值组合 对应的库存ID
    // Map不加泛型 对代码性能是否有影响呢？ 没有
    // 泛型不写 对编译有影响  对运行没有影响
    @Override
    @GmallCache(prefix="getSkuValueIdsMap")
    public Map getSkuValueIdsMap(Long spuId) {
        Map result = new HashMap();
        List<Map> listMap = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        listMap.forEach(map -> {
            //map.get("values_id");//K
            //map.get("sku_id");//V
            result.put(map.get("values_id"), map.get("sku_id"));
        });
        return result;
    }

    //查询所有一二三级分类视图 结果集
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }

    //查询当前库存的平台属性 入参：skuId
    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }

    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
}
